const DyClient = require("./DyClient/index");
const JavaClient = require("./JavaClient/index");
const sceneMap = require("./map/sceneMap");
const express = require("express");

const PORT = 3000;

const app = express();

app.get("/msg/connect", (req, res) => {
  const { liveId, sceneId } = req.query;
  console.log(`Connect ${liveId} to ${sceneId}`);
  if (liveId && sceneId) {
    const client = sceneMap.getClient(sceneId);
    if (!client) {
      sceneMap.addClient({
        sceneId,
        liveId,
      });
      const javaClient = new JavaClient(sceneId);
      javaClient.init(() => {
        const dyClient = new DyClient(sceneId);
        dyClient.init((msg) => {
          try {
            console.log(msg);
            javaClient.sendMsg(msg);
          } catch (err) {
            console.log("发生非预期情况 断开socket连接", err);
            javaClient.destroy();
            dyClient.destroy();
          }
        });
      });
    }
    // 响应200
    res.status(200).send("Connected");
  } else {
    res.status(400).send("Missing liveId or sceneId");
  }
});

app.get("/msg/disconnect", (req, res) => {
  const { sceneId } = req.query;
  console.log(`Disconnect ${sceneId}`);
  if (sceneId) {
    const client = sceneMap.getClient(sceneId);
    if (client) {
      client.javaClient && client.javaClient.destroy();
      client.dyClient && client.dyClient.destroy();
    }
    res.status(200).send("Connected");
  } else {
    res.status(400).send("Missing sceneId");
  }
});


app.get("/dymsg/send", (req, res) => {
  const { liveId, sceneId } = req.query;
  console.log(`Connect ${liveId} to ${sceneId}`);
  if (liveId && sceneId) {
    const client = sceneMap.getClient(sceneId);
    if (!client) {
      sceneMap.addClient({
        sceneId,
        liveId,
      });
      const javaClient = new JavaClient(sceneId);
      javaClient.init(() => {
        const dyClient = new DyClient(sceneId);
        dyClient.init((msg) => {
          try {
            javaClient.sendMsg(msg);
          } catch (err) {
            console.log("发生非预期情况 断开socket连接", err);
            javaClient.destroy();
            dyClient.destroy();
          }
        });
      });
    }
    // 响应200
    res.status(200).send("Connected");
  } else {
    res.status(400).send("Missing liveId or sceneId");
  }
});


app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});
